<template>
	<view class="margin-sm">
		<!-- 收货人 -->
		<use-list-title v-if="!(addrData && addrData.addressId)" class="margin-top-sm" type="round" color="#333" title="选择收货人" iconfont="icondizhi-" @goto="toaddr"></use-list-title>
		<view v-else class="use-area dflex-b" @click="toaddr">
			<view class="dflex">
				<view class="iconfont icondizhi- margin-right ft-main"></view>
				<view class="w-full dflex-wrap-w">
					<view class="margin-bottom-xs clamp-1">
						<text>{{ addrData.detailedAddress }}</text>
					</view>
					<view>
						<text>{{ addrData.contacts }}</text>
						<text class="margin-left">{{ addrData.showMobile }}</text>
					</view>
				</view>
			</view>

			<view class="iconfont iconjiantou-01 fs-sm"></view>
		</view>

		<view class="goods-area use-area">
			<!-- 商品列表 -->
			<view class="goods-item" >
				<view class="pos-r">
					<image mode="aspectFill" :src="goodsData.pic"></image>
					<view v-if="(goodsData.reserveCount < 10 || goodsData.reserveCount < goodsData.goods_num)"
						class="disabled dflex-c dflex-flow-c pos-a pos-tl-c border-radius-c">
						<text class="fs-xs">库存不足</text>
						<text class="margin-left-xs fs-xxs" v-if="goodsData.reserveCount > 0">剩余{{goodsData.reserveCount}}</text>
					</view>
					
					<view v-if="goodsData.isNew===1" class="use-tag pos-a pos-top bg-base margin-right-sm">新品</view>
				</view>
				<view class="flex1 padding-left-sm">
					<text class="title clamp-2">{{ goodsData.title || '' }}</text>
					<view class="ft-dark fs-xs padding-top-xs clamp-2">
						<text  class="margin-right-sm">{{goodsData.intro}}</text>
					</view>
					<view class="pos-r dflex-b padding-top-lg" v-if="goodsData.goods_num">
						<view class="dflex">
							<view class="price flex1">{{ goodsData.sellPrice }}</view>
						</view>
						<!-- + - 数量 -->
						<use-number-box  :min="1" :max="goodsData.reserveCount"
							:value="goodsData.goods_num > goodsData.reserveCount ? goodsData.reserveCount : goodsData.goods_num"
							:is-max="goodsData.goods_num >= goodsData.reserveCount" :is-min="goodsData.goods_num === 1"
							 direction="right" @eventChange="numberChange"></use-number-box>
					</view>
				</view>
			</view>
		</view>
		<view class="gap"></view>
		
		<!-- 金额明细 -->
		<view class="use-area">
			<view class="dflex-b line-height-item">
				<view class="flex1">总金额</view>
				<view class="ft-base">￥{{ goods_money }}</view>
			</view>
			<view class="dflex-b line-height-item">
				<view class="flex1">配送费</view>
				<view class="ft-base">￥{{ goodsData.expressFee }} x {{goodsData.goods_num}}</view>
			</view>
			
		</view>
		
		<view class="gap"></view>
		<!-- 优惠券 -->
		<!-- <use-list-title title="银行卡" type="round" :tip="couponName" color="#333" iconfont="iconyixiaoshou" @goto="couponShow = true"></use-list-title> -->
		<!-- 优惠券弹出层 -->
		<use-popup mode="bottom" bgclass=" " v-model="couponShow">
			<!-- 优惠券区 -->
			<scroll-view>
				<view class="coupon-area padding bg-drak border-radius-top30 safe-area-inset-bottom">
					<view class="coupon-item bg-main pos-r fs-xs" v-for="(item, index) in banks" :key="index">
						<view class="content pos-r padding dflex-b">
							<view class="">
								<view class="margin-bottom-xs fs">{{ item.bankName }}</view>
								<view class="ft-dark">卡号：{{ item.showAccount}}</view>
							</view>
							<view class="tar">
								<text v-if="bankIndex==index" style="background-color: rgba(182,91,93,0.4); color: #b65b5d;border: 1px solid #b65b5d;"
									class="fs-xs border-radius-lg padding-tb-xs padding-lr-sm">已选择</text>
								<text v-else @click="bankIndex=index" style="color: #b65b5d;border: 1px solid #b65b5d;"
									class="fs-xs border-radius-lg padding-tb-xs padding-lr-sm">选择</text>
							</view>
			
							<view class="circle l"></view>
							<view class="circle r"></view>
						</view>
					</view>
					
					<view v-if="!(banks && banks.length > 0)" class="coupon-none">
						<text class="coupon-none-tip">无可用银行卡</text>
					</view>
				</view>
			</scroll-view>
				
		</use-popup>

		<view class="use-area">
			<view class="margin-right-xl">请完善手机号</view>
			<input class="bg-drak w-full border-radius-sm margin-top-sm padding" 
				v-model="addrData.mobile" maxlength="200" auto-height placeholder="请完善收货人手机号"/>
		</view>

		<view class="gap"></view>
		<!-- 底部  -->
		<view class="oper-area pos-f pos-b-full w-full dflex-b bg-main safe-area-inset-bottom padding-lr-sm">
			<view>
				<text class="fs-sm">实付款</text>
				<text class="price margin-left-sm fs-xl">{{ total_money }}</text>
			</view>
			<view class="submit dflex-c bg-base border-radius-big padding-lr animated-all" :class="is_submit === 1 ? 'bg-disabled' : ''" @click="submit">提交订单</view>
		</view>
	</view>
</template>

<script>
	import { mapState } from 'vuex';
	import {goods_detail} from "../../js_sdk/apis/goods.js"
	import { address_list } from "../../js_sdk/apis/address.js"
	import {get_account,update_openid} from "../../js_sdk/apis/user.js"
	import {order_save,goods_wxredeem,goods_redeem,get_order_by_id} from "../../js_sdk/apis/order.js"
	export default {
		computed: {
			userInfo(){
				return this.$store.state.user.userInfo
			},
			isLogin(){
				return this.$store.getters['user/hasLogin']
			}
		},
		data() {
			return {
				// 收货地址
				addrData: {},
				// 商品数据
				goodsData: {},
				// 产品金额
				goods_money: 0,
				outTradeNo:"",
				couponShow:false,
				couponName:"选择银行卡",
				bank:{},
				bankIndex:0,
				phone:"",
				banks:[],
				// 实付金额
				total_money: 0,
				cashoutPopup:false,
				// 优惠金额
				total_coupon_money: 0,
				// 买家备注
				order_desc: '',
				is_submit: 1
			};
		},
		watch: {
			//显示空白页
			bankIndex(e) {
				console.log(e)
				this.bank=this.banks[e]
				this.couponName=this.bank.bankName+"("+this.bank.showAccount+")"
			}
		},
		onShow() {
			this.$store.dispatch('user/GetInfo')
		},
		onLoad(options) {
			let _this = this;
			if(getApp().globalData.goods){
				// 商品 ids
				this.goods_id = options.goods_id || '';
				// 商品数量 
				this.goodsData= getApp().globalData.goods
				this.goodsData.goods_num = parseInt(options.goods_num || 1);
				this.calcTotalMoney()
			}else{
				goods_detail({id:options.goods_id}).then(res=>{
					this.goodsData=res.data
					this.goodsData.goods_num = parseInt(options.goods_num || 1);
					getApp().globalData.goods=res.data
					this.calcTotalMoney()
				})
			}
			address_list().then(res=>{
				this.addrData=res.data.content.filter(v=>v.isDefault)[0]||{}
				this.is_submit = 0;
			})
			get_account().then(res=>{
				this.banks=res.data.content
				this.bank=this.banks&&res.data.content[this.bankIndex]
				if(this.bank){
					this.couponName=this.bank.bankName+"("+this.bank.showAccount+")"
				}
			})
			uni.$on('__event_choice_address', data => {
				this.$set(this.addrData,"detailedAddress",data.detailedAddress)
				this.$set(this.addrData,"contacts",data.contacts)
				this.$set(this.addrData,"addressId",data.addressId)
				this.$set(this.addrData,"showMobile",data.showMobile)
			});
		},
		methods: {
			// 计算实际支付 总金额
			calcTotalMoney() {
				this.goods_money=(this.goodsData.goods_num*this.goodsData.sellPrice).toFixed(2)
				this.total_money =(Number(this.goods_money)+(this.goodsData.goods_num*this.goodsData.expressFee)).toFixed(2)
			},
			// +- 下单数量
			numberChange(options) {
				this.goodsData.goods_num = options.number
				this.calcTotalMoney();
			},
			// 提交订单
			async submit() {
				if (!(this.addrData && this.addrData.addressId)) {
					this.$api.msg('请选择收货人');
					return;
				}
				if (!this.addrData.mobile||this.addrData.mobile.length!=11) {
					this.$api.msg('请完善手机号');
					return;
				}
				// #ifdef APP-PLUS || H5
				await this.$store.dispatch('user/GetInfo')
				uni.showModal({
					title:"确认提示",
					content:this.goodsData.pvPrice>=299?"确认提交订单？":"您购买的商品未达到299pv的基础复消，确定是否下单",
					success: (res) => {
						if(res.confirm){
							this.cashoutPopup=false
							this.is_submit = 1;
							let _this = this;
							uni.showActionSheet({
								itemList: [
									Number(this.userInfo.sysBalance)<Number(this.total_money)?'账户余额不足('+this.userInfo.sysBalance+'请充值)':'账户余额支付(剩余'+this.userInfo.sysBalance+')',
									Number(this.userInfo.earmarkedMoney)<Number(this.total_money)?'消费专项金不足('+this.userInfo.earmarkedMoney+')':'消费专项金支付(剩余'+this.userInfo.earmarkedMoney+')'
								],
								success:(res)=> {
									if(res.tapIndex==0&&Number(this.userInfo.sysBalance)<Number(this.total_money)){
										uni.navigateTo({
											url:"../../pagesA/user/wallet/wallet"
										})
									}else{
										let obj = {
											productId:_this.goodsData.id,
											number: _this.goodsData.goods_num,
											contacts: _this.addrData.contacts,
											shippingAddress:_this.addrData.detailedAddress,
											mobile: _this.addrData.mobile,
											payType:0
										};
										if(res.tapIndex==1){//消费专项金支付
											obj.payType=3
										}
										goods_redeem(obj).then(res=>{
											console.log(res)
											if (res.code === 200) {
												// 跳转支付页
												uni.showToast({
													icon:"success",
													title:"购买成功"
												})
												_this.$api.timerout(() => {
													uni.redirectTo({
														url:"../../pages/user/order/order-intergral?type=0"
													})
												}, 800);
												return;
											}
											_this.$api.msg(res.msg);
											_this.$api.timerout(() => {
												_this.is_submit = 0;
											}, 1000);
										})
									}
								}
							});
							
						}
					}
				})
				// #endif
				// #ifdef MP-WEIXIN
				uni.showLoading({
					title: "创建订单中"
				})
				let code=await uni.login({
					provider: 'weixin'
				})
				code = code[1].code
				let res=await this.$yunapi('user-center', 'loginByWeixin', {code})
				console.log(res)
				uni.setStorageSync('uniIdToken', res.token)
				uni.setStorageSync('uni_id_token_expired', res.tokenExpired)
				if(!this.userInfo.openid){
					let openid=res.userInfo.wx_openid["mp-weixin"]
					let res2=await update_openid({openid})
				}
				await this.$store.dispatch('user/GetInfo')
				let res3=await goods_wxredeem({
					productId:this.goodsData.id,
					number: this.goodsData.goods_num,
					contacts: this.addrData.contacts,
					shippingAddress:this.addrData.detailedAddress,
					mobile: this.addrData.mobile
				})
				console.log(res3)
				this.pay(res3)
				// #endif
			},
			pay(res){
				uniCloud.callFunction({
				  name: 'pay',
				  data: {
				    provider:"wxpay",
				    outTradeNo: res.data.id,
					userOrder:res.data
				  }
				}).then(res=>{
					console.log(res);
					if (res.result.orderInfo) {
					  return new Promise((resolve, reject) => {
					    uni.requestPayment({
					      // #ifdef MP-WEIXIN
					      ...res.result.orderInfo,
					      // #endif
					      
					      complete() {
						uni.hideLoading()
					        resolve(res.result.outTradeNo)
					      }
					    })
					  })
					} else {
						uni.hideLoading()
					  throw new Error(res.result.msg)
					}
				}).then(outTradeNo=>{
					this.checkPay(outTradeNo)
				})
			},
			checkPay(outTradeNo){
				get_order_by_id({id:outTradeNo}).then(res=>{
					if(res.data.status==-2){
						uni.showModal({
							title:"提示"	,
							content:"未支付成功",
							confirmText:"刷新",
							success: (re) => {
								if(re.confirm){
									this.checkPay(outTradeNo)
								}
							}
						})
					}else{
						uni.showModal({
							title:"提示"	,
							content:"支付成功",
							success: (re) => {
								uni.redirectTo({
									url:"../../pages/user/order/order-intergral?status=-1"
								})
							}
						})
					}
				})
			},
			// 选择收货人
			toaddr() {
				uni.navigateTo({
					url: '/pages/user/address/address?source=1',
					complete() {}
				});
			}
		}
	};
</script>

<style lang="scss">
	page {
		background: $page-color-base;
		padding-bottom: 100rpx;
	}

	.goods-area {
		.goods-item {
			display: flex;

			.title {
				height: 72rpx;
			}

			.disabled {
				color: #fff !important;
				width: 120rpx;
				height: 120rpx;
				background-color: rgba(51, 51, 51, 0.5);
			}

			image {
				flex-shrink: 0;
				display: block;
				width: 180rpx;
				height: 180rpx;
				border-radius: 4rpx;
			}
		}
	}

	.oper-area {
		z-index: 998;
		box-shadow: 0 -1px 5px rgba(0, 0, 0, 0.05);
		height: 100rpx;
		height: calc(env(safe-area-inset-bottom) + 100upx);

		.submit {
			height: 66rpx;
		}
	}

	/* 优惠券区 */
	.coupon-area {
		max-height: 60vh;
		overflow: auto;

		.coupon-item {
			margin-bottom: 20rpx;

			&:last-child {
				margin-bottom: 0;
			}

			.content {
				&:after {
					position: absolute;
					left: 0;
					bottom: 0;
					content: '';
					width: 100%;
					height: 0;
					border-bottom: 1px dashed #f3f3f3;
					transform: scaleY(50%);
				}
			}

			.circle {
				position: absolute;
				bottom: -10rpx;
				z-index: 10;
				width: 20rpx;
				height: 20rpx;
				background: #f5f5f5;
				border-radius: 50%;

				&.r {
					right: -6rpx;
				}

				&.l {
					left: -6rpx;
				}
			}
		}
	}
.cashout {
		padding: 15rpx 60rpx;
		background-color: #fff;
		border-radius: 15rpx;
	}

	.cashout-area {
		width: 80vw;
		padding: 80rpx;

		.field {
			padding: 20rpx;
			background-color: #f5f5f5;

			input {
				height: 56rpx;
				line-height: 56rpx;
			}
		}
	}
	.coupon-none {
		width: 100%;
		height: 100%;
		line-height: 30vh;
		display: flex;
		align-items: center;
		justify-content: center;

		.coupon-none-tip {
			color: #909399;
		}
	}
</style>
